import { login, logout, getInfo } from '@/api/user'
import {loginApi, currentAdminInfoApi } from '@/api/back';

import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    user_info: {},
    user_data: {},
    token: '',
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, info) => {
    state.user_info = info
  },
  SET_USER_DATA: (state, user_data) => {
    state.user_data = user_data
  },

  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      loginApi({ account: username.trim(), pwd: password }).then(response => {
        const { data } = response
        console.log('response', response);

        commit('SET_TOKEN', data.token)

        commit('SET_NAME', data.user_info.account);
        commit('SET_AVATAR', 'https://youpin.nuok.com/uploads/attach/2023/02/20230208/1d6c47741a776caf16530621ff4ed359.png')

        commit('SET_USER_INFO', data.user_info)
        commit('SET_USER_DATA', data)

        localStorage.setItem('token', data.token);

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      currentAdminInfoApi().then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { account, avatar } = data

        commit('SET_NAME', account)
        commit('SET_AVATAR', 'https://youpin.nuok.com/uploads/attach/2023/02/20230208/5d3a19d3f8a72b111593c4f4c1173153.png')

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        localStorage.clear();
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      localStorage.clear();
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

